#include "array.h"
#include <QMessageBox>
#include "../../layout/layout.hpp"
#include "../../undoRedo/undoRedo.hpp"
#include "../../utils/kutils.h"

namespace qbe::qbeArray {
void exit(ecs::Query query, state::AllModeType enter_mode) {}
void init(entt::registry& reg, ecs::Commands commands, ecs::Query query) {}
void update(entt::registry& ecs_reg, ecs::Query query, ecs::Bus& bus, ecs::EventWriter<msg::RenderEvent> event) {
  auto& state = query.get_resource<state::State>();

  // 仅在模式执行
  if (state.getEditingMode() != state::EditingModeType::Array)
    return;
  //获取当前操作的Cell
  auto& cmd = query.get_resource<layout::CellCmd>();
  auto cell = cmd.get_cell();
  auto& reg = cell->reg;
  auto& cell_state = query.get_resource<layout::CellState>();
  //获取选择对象
  std::vector<entt::entity> select_arr;
  for (auto [e] : reg.view<select::SelectTag>().each()) {
    select_arr.push_back(e);
  }
  if (select_arr.empty()) {
    state.exit();
    return;
  }

  auto& param = query.get_resource<ArrayModel>();
  if (param.is_open_ui == false) {
    auto graphs = qbe::auxiliary::getGraph(cell, select_arr);
    auto max_box = qbe::auxiliary::calBonndingBox(graphs);
    bus.send(UiMessage::ArrayUi_Open{max_box});
    param.is_open_ui = true;

    //界面取消按钮处理
    {
      auto res = bus.receive<UiMessage::ArrayUi_Cancel>();
      if (!res.empty()) {
        bus.send(UiMessage::ArrayUi_Close());
        param.is_open_ui = false;
        state.exit();
      }
    }
  }

  auto res = bus.receive<UiMessage::ArrayUi_Ok>();
  if (!res.empty()) {
    // 获取鼠标事件
    auto& hand = query.get_resource<vsg::ref_ptr<input::HandleBundle>>();

    //获取坐标轴
    auto& axis_t = query.get_resource<vsg::ref_ptr<input::HandleBundle>>();

    auto& reg = cell->reg;
    auto& cell_state = query.get_resource<layout::CellState>();

    //判断引脚编号是否超过范围
    unsigned int max_number = cell->max_pin_id;
    int count = res[0].row * res[0].col;
    for (auto sel_ele : select_arr) {
      for (int i = 1; i < count; i++) {
        auto pin = reg.try_get<qlib::Pin::s_ptr>(sel_ele);
        if (pin) {
          unsigned int _pin_number = ++max_number;
          if (_pin_number > 100000) {
            QMessageBox::information(nullptr, QObject::tr("Information"), QObject::tr("The max pin number is 100000!"), QMessageBox::Ok);
            //界面取消按钮处理
            {
              auto res = bus.receive<UiMessage::ArrayUi_Cancel>();
              if (!res.empty()) {
                bus.send(UiMessage::ArrayUi_Close());
                param.is_open_ui = false;
                state.exit();
              }
            }
            return;
          }
        }
      }
    }
    //更新最大引脚编号
    qbe::auxiliary::UpdateCellMaxPinId(cell);
    std::unordered_map<entt::entity, entt::entity> all_entitys_map;
    std::vector<std::any> all_new_graphs;
    for (auto sel_ele : select_arr) {
      // 获取选中对象包围盒与中心
      auto graphs = qbe::auxiliary::getGraph(cell, {sel_ele});
      auto box = qbe::auxiliary::calBonndingBox(graphs);
      auto center = (box[0] + box[1]) / 2;

      int row = res[0].row;
      int col = res[0].col;
      qlib::Vec2<double> row_vector(res[0].row_x, res[0].row_y);
      qlib::Vec2<double> col_vector(res[0].col_x, res[0].col_y);
      auto position = qbe::auxiliary::calArrayPosition(center.x, center.y, row, col, row_vector, col_vector);
      for (int i = 1; i < position.size(); i++) {

        //复制选择的对象
        std::vector<entt::entity> vec_entity{sel_ele};
        auto copy_graph = qbe::auxiliary::copyElement(cell, vec_entity);
        for (auto i : copy_graph) {
          const std::type_info& stored_type = i.type();
          if (stored_type == typeid(qlib::Pin::s_ptr)) {
            auto pin = std::any_cast<qlib::Pin::s_ptr>(i);

            QStringList pin_text_list = QString::fromStdString(pin->text).split(",");
            if (pin_text_list.size() != 3) {
              continue;
            }
            std::string pin_type = pin_text_list[2].toStdString();
            std::string _pin_number = QString::number(cell->getPinMaxId()).toStdString();

            std::string _pin_text = _pin_number + "," + _pin_number + "," + pin_type;
            pin->text = _pin_text;
          }
        }
        qlib::Vec2d vec = position[i] - center;
        qbe::auxiliary::translateGraph(copy_graph, vec);
        all_new_graphs.insert(all_new_graphs.end(), copy_graph.begin(), copy_graph.end());
      }
    }

    auto new_entitys = auxiliary::AddGraphToCell(cell, all_new_graphs);

    auto& layout_cmd = query.get_resource<layout::LayoutCmd>();
    for (auto e : new_entitys) {
      layout_cmd.add(e);
    }
    //event.send(msg::RenderEvent{msg::RenderCode::CellUpdate});  //确定后版图更新
    layout_cmd.render_update();  //确定后版图更新
    //获取undo/red0
    auto& unredoMoudel = query.get_resource<undoRedoT::UndoRedoModule>();
    unredoMoudel.start(cell);
    for (auto e : new_entitys)
      unredoMoudel.add(e);
    unredoMoudel.end();

    state.exit();

    if (param.is_open_ui == true) {
      bus.send(UiMessage::ArrayUi_Close());
      param.is_open_ui = false;
    }
  }
  //界面取消按钮处理
  {
    auto res = bus.receive<UiMessage::ArrayUi_Cancel>();
    if (!res.empty()) {
      bus.send(UiMessage::ArrayUi_Close());
      param.is_open_ui = false;
      state.exit();
    }
  }
}
void post(entt::registry& reg, ecs::Commands commands, ecs::Query query, ecs::Bus& bus) {}

}  // namespace qbe::qbeArray